import React, { useState, useEffect } from 'react'
import { Card, Row, Col, Space, Typography, Progress, Statistic } from 'antd'
import { 
  WifiOutlined, 
  ThunderboltOutlined, 
  ClockCircleOutlined,
  DatabaseOutlined,
  CameraOutlined,
  ExperimentOutlined
} from '@ant-design/icons'
import { useWebSocket } from '../../hooks/useWebSocket'
import { Utils } from '../../utils'
import './StatusBar.css'

const { Text } = Typography

const StatusBar = () => {
  const { 
    connected, 
    connectionStatus, 
    pendulumState, 
    backendLogs, 
    serialLogs 
  } = useWebSocket()
  
  const [systemStats, setSystemStats] = useState({
    fps: 0,
    latency: 0,
    dataPoints: 0,
    experimentTime: 0,
    lastUpdate: null
  })

  // 更新系统统计
  useEffect(() => {
    if (pendulumState) {
      setSystemStats(prev => ({
        ...prev,
        fps: pendulumState.fps || 0,
        latency: pendulumState.latency || 0,
        experimentTime: pendulumState.time || 0,
        dataPoints: (backendLogs?.length || 0) + (serialLogs?.length || 0),
        lastUpdate: new Date()
      }))
    }
  }, [pendulumState, backendLogs, serialLogs])

  // 获取连接状态信息
  const getConnectionInfo = () => {
    switch (connectionStatus) {
      case 'connected':
        return {
          status: 'success',
          text: 'WebSocket已连接',
          color: '#52c41a',
          icon: <WifiOutlined />
        }
      case 'connecting':
        return {
          status: 'active',
          text: '正在连接...',
          color: '#1890ff',
          icon: <WifiOutlined />
        }
      case 'disconnected':
        return {
          status: 'exception',
          text: 'WebSocket已断开',
          color: '#faad14',
          icon: <WifiOutlined />
        }
      case 'error':
        return {
          status: 'exception',
          text: 'WebSocket错误',
          color: '#f5222d',
          icon: <WifiOutlined />
        }
      default:
        return {
          status: 'normal',
          text: '等待连接',
          color: '#d9d9d9',
          icon: <WifiOutlined />
        }
    }
  }

  // 获取性能等级
  const getPerformanceLevel = (value, thresholds) => {
    if (value >= thresholds.excellent) return { level: 'excellent', color: '#52c41a' }
    if (value >= thresholds.good) return { level: 'good', color: '#1890ff' }
    if (value >= thresholds.fair) return { level: 'fair', color: '#faad14' }
    return { level: 'poor', color: '#f5222d' }
  }

  const connectionInfo = getConnectionInfo()
  
  // FPS性能评级
  const fpsPerf = getPerformanceLevel(systemStats.fps, {
    excellent: 25,
    good: 15,
    fair: 10
  })
  
  // 延迟性能评级（数值越小越好）
  const latencyPerf = getPerformanceLevel(200 - systemStats.latency, {
    excellent: 150, // 延迟 < 50ms
    good: 100,      // 延迟 < 100ms
    fair: 50        // 延迟 < 150ms
  })

  return (
    <Card 
      className="status-bar"
      size="small"
      title={
        <Space>
          <ExperimentOutlined style={{ color: '#4fc3f7' }} />
          <span>系统状态</span>
        </Space>
      }
    >
      <Row gutter={[16, 8]}>
        {/* 连接状态 */}
        <Col xs={24} sm={12} md={6}>
          <div className="status-item">
            <Space>
              {connectionInfo.icon}
              <div>
                <Text style={{ fontSize: '12px', color: '#999' }}>连接状态</Text>
                <div>
                  <Text 
                    style={{ 
                      fontSize: '13px', 
                      color: connectionInfo.color,
                      fontWeight: 'bold'
                    }}
                  >
                    {connectionInfo.text}
                  </Text>
                </div>
              </div>
            </Space>
          </div>
        </Col>

        {/* FPS */}
        <Col xs={24} sm={12} md={6}>
          <div className="status-item">
            <Space>
              <ThunderboltOutlined style={{ color: fpsPerf.color }} />
              <div>
                <Text style={{ fontSize: '12px', color: '#999' }}>帧率</Text>
                <div>
                  <Text 
                    style={{ 
                      fontSize: '16px', 
                      color: fpsPerf.color,
                      fontWeight: 'bold',
                      fontFamily: 'monospace'
                    }}
                  >
                    {Math.round(systemStats.fps)}
                  </Text>
                  <Text style={{ fontSize: '11px', color: '#999', marginLeft: '2px' }}>
                    FPS
                  </Text>
                </div>
              </div>
            </Space>
          </div>
        </Col>

        {/* 延迟 */}
        <Col xs={24} sm={12} md={6}>
          <div className="status-item">
            <Space>
              <ClockCircleOutlined style={{ color: latencyPerf.color }} />
              <div>
                <Text style={{ fontSize: '12px', color: '#999' }}>延迟</Text>
                <div>
                  <Text 
                    style={{ 
                      fontSize: '16px', 
                      color: latencyPerf.color,
                      fontWeight: 'bold',
                      fontFamily: 'monospace'
                    }}
                  >
                    {Math.round(systemStats.latency)}
                  </Text>
                  <Text style={{ fontSize: '11px', color: '#999', marginLeft: '2px' }}>
                    ms
                  </Text>
                </div>
              </div>
            </Space>
          </div>
        </Col>

        {/* 数据点数 */}
        <Col xs={24} sm={12} md={6}>
          <div className="status-item">
            <Space>
              <DatabaseOutlined style={{ color: '#1890ff' }} />
              <div>
                <Text style={{ fontSize: '12px', color: '#999' }}>数据点</Text>
                <div>
                  <Text 
                    style={{ 
                      fontSize: '16px', 
                      color: '#1890ff',
                      fontWeight: 'bold',
                      fontFamily: 'monospace'
                    }}
                  >
                    {systemStats.dataPoints}
                  </Text>
                </div>
              </div>
            </Space>
          </div>
        </Col>

        {/* 性能指示器 */}
        <Col span={24}>
          <div className="performance-indicators">
            <Row gutter={8}>
              <Col span={8}>
                <div className="indicator-item">
                  <Text style={{ fontSize: '11px', color: '#999' }}>连接质量</Text>
                  <Progress
                    percent={connected ? 100 : 0}
                    size="small"
                    strokeColor={connectionInfo.color}
                    showInfo={false}
                    trailColor="rgba(255, 255, 255, 0.1)"
                  />
                </div>
              </Col>
              <Col span={8}>
                <div className="indicator-item">
                  <Text style={{ fontSize: '11px', color: '#999' }}>帧率质量</Text>
                  <Progress
                    percent={Math.min((systemStats.fps / 30) * 100, 100)}
                    size="small"
                    strokeColor={fpsPerf.color}
                    showInfo={false}
                    trailColor="rgba(255, 255, 255, 0.1)"
                  />
                </div>
              </Col>
              <Col span={8}>
                <div className="indicator-item">
                  <Text style={{ fontSize: '11px', color: '#999' }}>响应质量</Text>
                  <Progress
                    percent={Math.max(100 - (systemStats.latency / 200) * 100, 0)}
                    size="small"
                    strokeColor={latencyPerf.color}
                    showInfo={false}
                    trailColor="rgba(255, 255, 255, 0.1)"
                  />
                </div>
              </Col>
            </Row>
          </div>
        </Col>

        {/* 实验时间和最后更新时间 */}
        <Col span={24}>
          <div className="time-info">
            <Row gutter={16}>
              <Col span={12}>
                <Space>
                  <ExperimentOutlined style={{ color: '#52c41a', fontSize: '12px' }} />
                  <Text style={{ fontSize: '11px', color: '#999' }}>
                    实验时间: 
                    <span style={{ color: '#52c41a', fontFamily: 'monospace', marginLeft: '4px' }}>
                      {Utils.formatTime(systemStats.experimentTime)}s
                    </span>
                  </Text>
                </Space>
              </Col>
              <Col span={12}>
                <Space>
                  <ClockCircleOutlined style={{ color: '#999', fontSize: '12px' }} />
                  <Text style={{ fontSize: '11px', color: '#999' }}>
                    更新: 
                    <span style={{ color: '#999', marginLeft: '4px' }}>
                      {systemStats.lastUpdate ? 
                        systemStats.lastUpdate.toLocaleTimeString() : 
                        '--:--:--'
                      }
                    </span>
                  </Text>
                </Space>
              </Col>
            </Row>
          </div>
        </Col>
      </Row>
    </Card>
  )
}

export default StatusBar
